package com.itheima.health.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendValidateCode(String type, String telephone) {
        log.info("[验证码-发送]type:{},telephone:{}", type, telephone);
        int code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
        log.debug("[发送短信]code:{}", code);
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + type + ":" + telephone;
        log.info("redisKey is:{},code is:{}", redisKey, code);
        redisTemplate.boundValueOps(redisKey).set(String.valueOf(code), 5 * 60L, TimeUnit.SECONDS);
        /////////////////////下面代码由阿里云代码模板生成//////////////////

//        // 这里无需真的将短信发送出去，测试过程中，我们直接在日志中查看打印的验证码即可
//        //构造请求参数
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain("dysmsapi.aliyuncs.com");
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-hangzhou");
//        request.putQueryParameter("PhoneNumbers", phone);
//        request.putQueryParameter("SignName", "传智健康项目");
//        request.putQueryParameter("TemplateCode", "SMS_175060789");
//        request.putQueryParameter("TemplateParam", "	{\"assertCode\":\"" + code + "\"}");
//        try {
//            //发起请求
//            CommonResponse response = acsClient.getCommonResponse(request);
//            log.info("[短信-发送验证码]response:{}", response.getData());
//        } catch (ClientException e) {
//            log.error("[短信-发送验证码]", e);
//        }

    }

    @Override
    public boolean checkValidateCode(String type, String telephone, String validateCode) {
        log.info("[短信-验证码效验]type:{},telephone:{},code:{}", type, telephone, validateCode);
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + type + ":" + telephone;
        String expectVal = (String) redisTemplate.boundValueOps(redisKey).get();
        if (!StringUtils.isEmpty(expectVal) && expectVal.equals(validateCode)) {
            redisTemplate.delete(redisKey);
            return true;
        } else {
            return false;
        }
    }
}
